package com.ruoyi.common.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * spring redis 工具类
 * 
 * @author ruoyi
 **/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisTemplateListService
{
    @Autowired
    public RedisTemplate redisTemplate;


    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * List右边添加一条数据
     *
     * @param key 缓存的键值
     * @param value 待缓存的值
     * @return 缓存的对象
     */
    public <T> long rightPush(final String key, T value)
    {
        Long count = redisTemplate.opsForList().rightPush(key, value);
        return count == null ? 0 : count;
    }

    /**
     * List左边边添加一条数据
     *
     * @param key 缓存的键值
     * @param value 待缓存的值
     * @return 缓存的对象
     */
    public <T> long leftPush(final String key, T value)
    {
        Long count = redisTemplate.opsForList().leftPush(key, value);
        return count == null ? 0 : count;
    }

    /**
     * List左边边添加一条数据
     *
     * @param key 缓存的键值
     * @param start 区间起始位置
     * @param end 区间结束位置
     * @return 缓存的对象
     */
    public <T> List<T> range(final String key, int start, int end)
    {
        // TODO 此方法获取值报错
        List<T> list = redisTemplate.opsForList().range(key, start, end);
        return list;
    }

    /**
     * list集合的大小
     * @param key 缓存的键值
     * @param <T> 待缓存的值类型
     * @return
     */
    public <T> long indexSize(final String key)
    {
        Long count = redisTemplate.opsForList().size(key);
        return count == null ? 0 : count;
    }

    /**
     *
     * @param key
     * @param <T>
     * @return
     */
    public <T> Object leftPop(final String key)
    {
        Object value = redisTemplate.opsForList().leftPop(key);
        return value;
    }
}
